<?php
/**
 * Created by PhpStorm.
 * User: kevin
 * Date: 15-6-16
 * Time: 下午7:42
 */
namespace Admin\Controller;
use Think\Controller;

class AdminController extends Controller {
    protected function _initialize(){
        /*判断用户是否登录*/
        define('UID', is_login());
        if(!UID){
            $this->redirect('Public/login');
        }

        /* 读取数据库中的配置 */
        $config =   S('DB_CONFIG_DATA');
        if(!$config){
            $config =   api('Config/lists');
            S('DB_CONFIG_DATA',$config);
        }
        C($config); //添加配置
        /*判断用户是否是管理员*/
       define('IS_ROOT',is_admin());
       if(!IS_ROOT){
           $AUTH = new \Think\Auth();
           $rule = MODULE_NAME.'/'.CONTROLLER_NAME.'/'.ACTION_NAME;
           if(!$AUTH->check($rule,UID)){
               $this->error('未授权访问');
           }
       }
       $this->assign('__MENU__',$this->getMenus());
    }
    /*
     * 获取菜单
     */
    public function getMenus($controller=CONTROLLER_NAME){
        $map['pid'] = 0;
        $map['hide'] =0;
        $map['module'] ='Admin';
        if(!C('DEVELOP_MODE')){ // 是否开发者模式
            $where['is_dev']    =   0;
        }
        $menus['main']  =   M('Menu')->where($map)->order('sort asc')->field('id,title,url')->select();
        $id=array();
        $menus['child'] = array();
        foreach($menus['main'] as $key =>$item){
            $AUTH = new \Think\Auth();
            $rule = MODULE_NAME.'/'.$item['url'];
            if(!IS_ROOT && !$AUTH->check($rule, UID)){
                unset($menus['main'][$key]);
                continue;
            }
            if(CONTROLLER_NAME.'/'.ACTION_NAME == $item['url']){
                $menus['main'][$key]['class'] = 'active';
            }
            $id[]=$item['id'];
        }
//        $pid = M('Nav')->where("pid !=0 AND url like '%{$controller}/".ACTION_NAME."%'")->getField('pid');
        //查找二级菜单
        $map['pid']=array('IN',$id);
        $rs =M('Menu')->where($map)->field('url')->select();
        $urls=array();
        foreach($rs as $key=>$item){
            $urls []= $item['url'];
        }
        $map0 =array();
        $map0['module'] = 'Admin';
        $map0['url'] =array('IN',$urls);
        // 查找当前子菜单
        $rs = M('Menu')->where($map0)->field('pid')->select();
        $pid=array();
        foreach($rs as $key=>$item){
            if($item['pid']!=0){
                $pid[]=$item['pid'];}
        }
        if($pid) {
            // 查找当前主菜单
            $map1 = array();
            $map1['pid'] = array('IN', $pid);
            $rs = M('Menu')->where($map1)->select();
            $nav['pid'] = array();
            foreach ($rs as $key => $item) {
                $nav['pid'][] = $item['pid'];
            }
            foreach ($menus['main'] as $key => $item) {
                // 获取当前主菜单的子菜单项
                $menus['main'][$key]['class'] = 'current';
                //生成child树
                $groups = M('Menu')->where(array('group' => array('neq', ''), 'pid' => $item['id']))->distinct(true)->getField("group", true);
                //获取二级分类的合法url
                $where = array();
                $where['pid'] = $item['id'];
                $where['hide'] = 0;
                if (!C('DEVELOP_MODE')) { // 是否开发者模式
                    $where['is_dev'] = 0;
                }
                $second_urls = M('Menu')->where($where)->getField('id,url');
                if (!IS_ROOT) {
                    $to_check_urls = array();
                    foreach ($second_urls as $key => $to_check_url) {
                        if (stripos($to_check_url, MODULE_NAME) !== 0) {
                            $rule = MODULE_NAME . '/' . $to_check_url;
                        } else {
                            $rule = $to_check_urls;
                        }
                        $AUTH = new \Think\Auth();
                        if ($AUTH->check($rule, UID)) {
                            $to_check_urls[] = $to_check_url;
                        }
                    }
                }
                foreach ($groups as $g) {
                    $map = array('group' => $g);
                    if (isset($to_check_urls)) {
                        if (empty($to_check_urls)) {
                            // 没有任何权限
                            continue;
                        } else {
                            $map['url'] = array('in', $to_check_urls);
                        }
                    }
                    $map['pid'] = $item['id'];
                    $map['hide'] = 0;
                    if (!C('DEVELOP_MODE')) { // 是否开发者模式
                        $map['is_dev'] = 0;
                    }
                    $menuList = M('Menu')->where($map)->field('id,pid,title,url,tip')->order('sort asc')->select();
                    $menus['child'][$g] = list_to_tree($menuList, 'id', 'pid', 'operater', $item['id']);
                }
            }
        }
//        var_dump($menus);
        return $menus;
    }

    protected function lists ($model,$where=array(),$order='',$field=true){
        $options    =   array();
        $REQUEST    =   (array)I('get.');
        if(is_string($model)){
            $model  =   M($model);
        }
        $OPT        =   new \ReflectionProperty($model,'options');
        $OPT->setAccessible(true);

        $pk         =   $model->getPk();
        if($order===null){
            //order置空
        }else if ( isset($REQUEST['_order']) && isset($REQUEST['_field']) && in_array(strtolower($REQUEST['_order']),array('desc','asc')) ) {
            $options['order'] = '`'.$REQUEST['_field'].'` '.$REQUEST['_order'];
        }elseif( $order==='' && empty($options['order']) && !empty($pk) ){
            $options['order'] = $pk.' desc';
        }elseif($order){
            $options['order'] = $order;
        }
        if(empty($where)){
            $where  =   array('status'=>array('egt',0));
        }
        if( !empty($where)){
            $options['where']   =   $where;
        }
        $options      =   array_merge( (array)$OPT->getValue($model), $options );
        $total        =   $model->where($options['where'])->count();
        if( isset($REQUEST['r']) ){
            $listRows = (int)$REQUEST['r'];
        }else{
            $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
        }
        $page = new \Think\Page($total, $listRows, $REQUEST);

        if($total>$listRows){
           /* $page->setConfig('prev','<<');
            $page->setConfig('next','>>');*/
            //$page->setConfig('theme','%TOTAL_PAGE% %HEADER% %FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE%');
            $page->setConfig('theme',' %HEADER% %FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%');
        }
        $p =$page->show();
        $this->assign('_page', $p? $p: '');
        $this->assign('_total',$total);
        $options['limit'] = $page->firstRow.','.$page->listRows;

        $model->setProperty('options',$options);
        $arr = $model->field($field)->select();
//        echo $model->getLastSql();die;
        return $arr;
    }

    //根据用户名获取用户ID
    protected function getUidByUsername($str){
        $map['username'] = $str;
        return M('User')->where($map)->getField(id);
    }

    //设置一条或者多条数据的状态
    public function setStatus($Model=CONTROLLER_NAME){
        $ids = I('request.ids');
        $status = I('request.status');
        if(empty($ids)){
            $this->error('请选择需要操作的数据');
        }
        $map['id'] = array('in',$ids);
        switch($status){
            case -1:
                $this->delete($Model,$map,array('success'=>'删除成功','error'=>'删除失败'));
                break;
            case 0:
                $this->forbid($Model,$map,array('success'=>'禁用成功','error'=>'禁用失败'));
                break;
            case 1:
                $this->resume($Model,$map,array('success'=>'启用成功','error'=>'启用失败'));
                break;
            default:
                $this->error('参数错误');
                break;
        }
    }

    //条目删除
    protected function delete($Model,$where=array(), $msg=array('success'=>'删除成功','error'=>'删除失败')){
        $res = $Model->where($where)->delete();
        if($res){
            $this->success($msg['success']);
        }else{
            $this->error($msg['error']);
        }
    }
}